package com.xunqi.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunqi.commonutils.R;
import com.xunqi.eduservice.entity.EduVideo;
import com.xunqi.eduservice.feign.VodFeign;
import com.xunqi.eduservice.mapper.EduVideoMapper;
import com.xunqi.eduservice.service.EduVideoService;
import com.xunqi.servicebase.exception.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author 夏沫止水
 * @since 2020-07-31
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private VodFeign vodFeign;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeVideoByCourseId(String courseId) {

        //根据课程id查询该课程下有多少小节
        List<EduVideo> eduVideoList = this.baseMapper.selectList(new QueryWrapper<EduVideo>().eq("course_id", courseId));

        int result = 0;

        //拿到videoId
        List<String> videoIds = eduVideoList.stream().map(e -> e.getVideoSourceId()).collect(Collectors.toList());

        //批量删除云视频
        R resultDelete = vodFeign.deleteBatch(videoIds);
        if (resultDelete.getCode() == 20001) {
            throw new GuliException(20001,"删除视频失败...熔断器");
        }

        for (EduVideo eduVideo : eduVideoList) {
            result = this.baseMapper.deleteById(eduVideo.getId());
        }

        // for (EduVideo eduVideo : eduVideoList) {
        //     if (eduVideo.getVideoSourceId() != null) {
        //         //删除云视频信息
        //         vodFeign.removeAliyVideo(eduVideo.getVideoSourceId());
        //     }
        //     //删除小节信息
        //     result = this.baseMapper.deleteById(eduVideo.getId());
        // }

        return result > 0;
    }

    @Override
    public EduVideo getVideoSourceIdByInfo(String videoSourceId) {

        EduVideo eduVideo = this.baseMapper.selectOne(new QueryWrapper<EduVideo>().eq("video_source_id", videoSourceId));

        return eduVideo;
    }
}
